{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "eb8acff8",
   "metadata": {},
   "outputs": [],
   "source": [
    "@dataclass\n",
    "class ContractData(BaseData):\n",
    "    \"\"\"\n",
    "    Contract data contains basic information about each contract traded.\n",
    "    \"\"\"\n",
    "    price_tick: float = 0                               #最小价格变动\n",
    "\n",
    "    margin_ratio : float = 0                            #保证金率\n",
    "    max_order_volume : float = 0                        #限价单最大单次委托量\n",
    "    open_commission_ratio : float = 0                   #开仓手续费率\n",
    "    open_commission : float = 0                         #开仓手续费\n",
    "    close_commission_ratio : float = 0                  #平仓手续费率\n",
    "    close_commission : float = 0                        #平仓手续费  \n",
    "    close_commission_today_ratio : float = 0            #平今手续费率\n",
    "    close_commission_today : float = 0                  #平今手续费\n",
    "CtpGateway里面加上\n",
    "\n",
    "import shelve\n",
    "#------------------------------------------------------------------------------------\n",
    "def remain_alpha(convert_contract:str) -> str:\n",
    "    \"\"\"\n",
    "    返回vt_symbol或者symbol的字母字符串\n",
    "    \"\"\"\n",
    "    if \".\" in convert_contract:\n",
    "        convert_contract = extract_vt_symbol(convert_contract)[0]\n",
    "    symbol_mark = \"\".join(list(filter(str.isalpha,convert_contract)))\n",
    "    return symbol_mark\n",
    "#-------------------------------------------------------------------------------------------------\n",
    "class CtpGateway(BaseGateway):\n",
    "    #-------------------------------------------------------------------------------------------------\n",
    "    def query_commission(self):\n",
    "        \"\"\"查询手续费数据\"\"\"\n",
    "        self.td_api.query_commission()\n",
    "    #-------------------------------------------------------------------------------------------------\n",
    "    def save_commission(self):\n",
    "        \"\"\"保存手续费数据\"\"\"\n",
    "        self.td_api.save_commission()\n",
    "    #-------------------------------------------------------------------------------------------------\n",
    "    def query_margin_ratio(self):\n",
    "        \"\"\"查询保证金率数据\"\"\"\n",
    "        self.td_api.query_margin_ratio()\n",
    "    #-------------------------------------------------------------------------------------------------\n",
    "    def save_margin_ratio(self):\n",
    "        \"\"\"保存保证金率数据\"\"\"\n",
    "        self.td_api.save_margin_ratio()\n",
    "    #-------------------------------------------------------------------------------------------------\n",
    "    def close(self):\n",
    "        \"\"\"\"\"\"\n",
    "        #关闭ctp api前保存手续费,保证金率数据到硬盘\n",
    "        self.save_commission()\n",
    "        self.save_margin_ratio()\n",
    "        self.td_api.close()\n",
    "        self.md_api.close()\n",
    "        self.query_functions = [self.query_account, self.query_position,self.query_commission,self.query_margin_ratio]\n",
    "tdapi里面加上\n",
    "\n",
    "class CtpTdApi(TdApi):\n",
    "    \"\"\"\"\"\"\n",
    "\n",
    "    def __init__(self, gateway):\n",
    "        self.commission_file_name = 'commission_data'\n",
    "        self.commission_file_path = get_folder_path(self.commission_file_name)        \n",
    "        self.commission_req = {}        #手续费查询字典   \n",
    "        self.commission_data = {}       #手续费字典\n",
    "        self.margin_ratio_file_name = 'margin_ratio_data'\n",
    "        self.margin_ratio_file_path = get_folder_path(self.margin_ratio_file_name)        \n",
    "        self.margin_ratio_req = {}        #保证金率查询字典   \n",
    "        self.margin_ratio_data = {}       #保证金率字典 \n",
    "        #读取硬盘存储手续费数据，保证金率数据\n",
    "        self.load_commission() \n",
    "        self.load_margin_ratio()\n",
    "    def onRspQryInstrument(self, data: dict, error: dict, reqid: int, last: bool): \n",
    "        \"\"\"合约查询回报\"\"\"        \n",
    "        contract = ContractData(\n",
    "            symbol=data[\"InstrumentID\"],\n",
    "            exchange=EXCHANGE_CTP2VT[data[\"ExchangeID\"]],\n",
    "            name=data[\"InstrumentName\"],\n",
    "            product=PRODUCT_CTP2VT.get(data[\"ProductClass\"], None),\n",
    "            size=data[\"VolumeMultiple\"],\n",
    "            price_tick=data[\"PriceTick\"],                    #合约最小价格变动\n",
    "            max_order_volume=data[\"MaxLimitOrderVolume\"],  #限价单次最大委托量\n",
    "            gateway_name=self.gateway_name)\n",
    "        symbol = contract.symbol\n",
    "        symbol_alpha = remain_alpha(symbol)\n",
    "        #手续费数据合并到contract\n",
    "        if symbol in list(self.commission_data):\n",
    "            contract.open_commission_ratio=self.commission_data[symbol][\"OpenRatioByMoney\"]                  #开仓手续费率\n",
    "            contract.open_commission=self.commission_data[symbol][\"OpenRatioByVolume\"]                       #开仓手续费\n",
    "            contract.close_commission_ratio=self.commission_data[symbol][\"CloseRatioByMoney\"]                #平仓手续费率\n",
    "            contract.close_commission=self.commission_data[symbol][\"CloseRatioByVolume\"]                     #平仓手续费\n",
    "            contract.close_commission_today_ratio=self.commission_data[symbol][\"CloseTodayRatioByMoney\"]     #平今手续费率\n",
    "            contract.close_commission_today=self.commission_data[symbol][\"CloseTodayRatioByVolume\"]          #平今手续费                \n",
    "        elif symbol_alpha in list(self.commission_data):\n",
    "            contract.open_commission_ratio=self.commission_data[symbol_alpha][\"OpenRatioByMoney\"]      #开仓手续费率\n",
    "            contract.open_commission=self.commission_data[symbol_alpha][\"OpenRatioByVolume\"]        #开仓手续费\n",
    "            contract.close_commission_ratio=self.commission_data[symbol_alpha][\"CloseRatioByMoney\"]    #平仓手续费率\n",
    "            contract.close_commission=self.commission_data[symbol_alpha][\"CloseRatioByVolume\"]          #平仓手续费\n",
    "            contract.close_commission_today_ratio=self.commission_data[symbol_alpha][\"CloseTodayRatioByMoney\"]#平今手续费率\n",
    "            contract.close_commission_today=self.commission_data[symbol_alpha][\"CloseTodayRatioByVolume\"]   #平今手续费\n",
    "        if symbol in  list(self.margin_ratio_data):                \n",
    "            contract.margin_ratio = self.margin_ratio_data[symbol][\"LongMarginRatioByMoney\"]       #合约保证金比率\n",
    "    #-------------------------------------------------------------------------------------------------\n",
    "    def onRspQryInstrumentCommissionRate(self, data: dict, error: dict, reqid: int, last: bool):\n",
    "        \"\"\"查询合约手续费率\"\"\"\n",
    "        symbol = data.get('InstrumentID',None)\n",
    "        if symbol:\n",
    "            self.commission_data[symbol] = data\n",
    "    #-------------------------------------------------------------------------------------------------\n",
    "    def onRspQryInstrumentMarginRate(self, data: dict, error: dict, reqid: int, last: bool):\n",
    "        \"\"\"查询保证金率\"\"\"\n",
    "        symbol = data.get('InstrumentID',None)\n",
    "        if symbol:\n",
    "            self.margin_ratio_data[symbol] = data\n",
    "    #-------------------------------------------------------------------------------------------------\n",
    "    def load_commission(self):\n",
    "        \"\"\"从硬盘读取手续费数据\"\"\"\n",
    "        f = shelve.open(f\"{self.commission_file_path}\\\\commission_data.vt\")\n",
    "        if 'data' in f:\n",
    "            d = f['data']\n",
    "            for key, value in list(d.items()):\n",
    "                self.commission_data[key] = value\n",
    "        f.close()\n",
    "    #-------------------------------------------------------------------------------------------------\n",
    "    def save_commission(self):\n",
    "        \"\"\"保存手续费数据到硬盘\"\"\"\n",
    "        f = shelve.open(f\"{self.commission_file_path}\\\\commission_data.vt\")\n",
    "        f['data'] = self.commission_data\n",
    "        f.close()         \n",
    "    #-------------------------------------------------------------------------------------------------\n",
    "    def load_margin_ratio(self):\n",
    "        \"\"\"从硬盘读取保证金率数据\"\"\"\n",
    "        f = shelve.open(f\"{self.margin_ratio_file_path}\\\\margin_ratio_data.vt\")\n",
    "        if 'data' in f:\n",
    "            d = f['data']\n",
    "            for key, value in list(d.items()):\n",
    "                self.margin_ratio_data[key] = value\n",
    "        f.close()\n",
    "    #-------------------------------------------------------------------------------------------------\n",
    "    def save_margin_ratio(self):\n",
    "        \"\"\"保存保证金率数据到硬盘\"\"\"\n",
    "        f = shelve.open(f\"{self.margin_ratio_file_path}\\\\margin_ratio_data.vt\")\n",
    "        f['data'] = self.margin_ratio_data\n",
    "        f.close() \n",
    "    #-------------------------------------------------------------------------------------------------\n",
    "    #commission_vt_symbol，margin_ratio_vt_symbol都是全市场合约列表，需要自己维护\n",
    "    #我用的合约连接交易所符号是'_'，用'.'自己替换\n",
    "    #-------------------------------------------------------------------------------------------------\n",
    "    def query_commission(self):\n",
    "        #查询手续费率\n",
    "        if len(commission_vt_symbol) > 0:\n",
    "            symbol = commission_vt_symbol[0].split('_')[0]\n",
    "            #手续费率查询字典\n",
    "            self.commission_req['BrokerID'] = self.brokerid\n",
    "            self.commission_req['InvestorID'] = self.userid\n",
    "            self.commission_req['InstrumentID'] = symbol\n",
    "            self.reqid += 1 \n",
    "            #请求查询手续费率\n",
    "            self.reqQryInstrumentCommissionRate(self.commission_req,self.reqid)  \n",
    "            commission_vt_symbol.pop(0)\n",
    "    def query_margin_ratio(self):\n",
    "        if len(margin_ratio_vt_symbol) > 0:\n",
    "            symbol = margin_ratio_vt_symbol[0].split('_')[0]\n",
    "            #保证金率查询字典\n",
    "            self.margin_ratio_req['BrokerID'] = self.brokerid\n",
    "            self.margin_ratio_req['InvestorID'] = self.userid\n",
    "            self.margin_ratio_req['InstrumentID'] = symbol\n",
    "            self.margin_ratio_req['HedgeFlag'] = THOST_FTDC_HF_Speculation\n",
    "            self.reqid += 1 \n",
    "            #请求查询保证金率\n",
    "            self.reqQryInstrumentMarginRate(self.margin_ratio_req,self.reqid)  \n",
    "            margin_ratio_vt_symbol.pop(0)\n",
    "trader\\ui，widget.py里面修改\n",
    "\n",
    "class ContractManager(QtWidgets.QWidget):\n",
    "    \"\"\"\n",
    "    Query contract data available to trade in system.\n",
    "    \"\"\"\n",
    "\n",
    "    headers = {\n",
    "        \"vt_symbol\": \"本地代码\",\n",
    "        \"symbol\": \"代码\",\n",
    "        \"exchange\": \"交易所\",\n",
    "        \"name\": \"名称\",\n",
    "        \"product\": \"合约分类\",\n",
    "        \"size\": \"合约乘数\",\n",
    "        \"price_tick\": \"价格跳动\",\n",
    "        \"min_volume\": \"最小委托量\",\n",
    "        \"margin_ratio\": \"保证金率\",\n",
    "        \"open_commission_ratio\": \"开仓手续费率\",\n",
    "        \"open_commission\": \"开仓手续费\",\n",
    "        \"close_commission_ratio\": \"平仓手续费率\",\n",
    "        \"close_commission\": \"平仓手续费\",\n",
    "        \"close_commission_today_ratio\": \"平今手续费率\",\n",
    "        \"close_commission_today\": \"平今手续费\",\n",
    "        \"gateway_name\": \"交易接口\",\n",
    "    }"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
